<template>
  <div class="comment-item">
    <!-- 评论头部：头像 + 用户名/内容/时间/回复 -->
    <div class="comment-header">
      <img
          :src="comment.userAvatar || defaultAvatar"
          class="avatar"
          :alt="`${comment.username || '用户'}的头像`"
      >
      <div class="user-content">
        <!-- 粉色用户名 -->
        <div class="username">@{{ comment.username || '匿名用户' }}</div>
        <!-- 评论内容（含@回复标识，level = 3才展示@） -->
        <div class="comment-text">
          <span v-if="comment.replyUserId && comment.level === 3" class="reply-at">
            回复 @{{ comment.replyUsername || '用户' }}：
          </span>
          <span style="font-size: 11px">{{ comment.content }}</span>
        </div>

        <!-- 时间 + 回复按钮 -->
        <div class="time-reply">
          <span class="time">{{ comment.time }}</span>
          <el-button
              size="mini"
              type="text"
              class="reply-btn"
              @click="showReply = true"
              :disabled="isSubmitting"
          >
            <span style="font-size: 9px" v-if="user.name">回复</span>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 回复输入框（缩进匹配头像宽度） -->
    <div class="reply-input" v-if="showReply">
      <el-input
          type="textarea"
          v-model.trim="replyContent"
          placeholder="输入回复内容..."
          rows="2"
          class="reply-textarea"
          :disabled="isSubmitting"
          @keyup.enter.native="submitReply"
      ></el-input>
      <div class="reply-btn-group">
        <el-button size="mini" @click="showReply = false" :disabled="isSubmitting">取消</el-button>
        <el-button size="mini" type="primary" @click="submitReply" :loading="isSubmitting">发送</el-button>
      </div>
    </div>

    <!-- 子评论列表：统一缩进嵌套 -->
    <div class="children-comments" v-if="hasChildren">
      <div class="children-list">
        <comment-item
            v-for="child in comment.children"
            :key="child.id"
            :comment="child"
            :fid="fid"
            :current-user="currentUser"
            :comment-level="commentLevel + 1"
            @refresh-comment="handleRefresh"
        ></comment-item>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'comment-item',
  props: {
    comment: {
      type: Object,
      required: true,
      // 仅保留核心必填字段校验
      validator: (value) => ['id', 'content', 'userId', 'time'].every(key => key in value)
    },
    fid: { type: Number, required: true },
    currentUser: { type: Object, default: () => ({}) },
    commentLevel: { type: Number, default: 1 } // 仅保留层级标记核心逻辑
  },
  data() {
    return {
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      showReply: false, // 回复框显示状态
      replyContent: '', // 回复内容
      isSubmitting: false, // 提交加载状态
      defaultAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' // 默认头像
    }
  },
  computed: {
    // 精简子评论判断：直接校验数组和长度
    hasChildren() {
      return Array.isArray(this.comment.children) && this.comment.children.length > 0;
    }
  },
  methods: {
    // 提交回复：仅保留核心请求逻辑，删除冗余日志
    submitReply() {
      if (this.isSubmitting) return;
      const content = this.replyContent.trim();

      // 基础校验：内容非空 + 已登录
      if (!content) return this.$notify.warning('请输入回复内容');
      if (!this.currentUser?.id) {
        this.$notify.warning('请先登录');
        this.showReply = false;
        return;
      }

      this.isSubmitting = true;
      this.$request({
        url: '/comment',
        method: 'POST',
        data: {
          content,
          fid: this.fid,
          // 精简层级逻辑：直接用 rootId 判断父ID
          pid: this.comment.rootId === 0 ? this.comment.id : this.comment.pid,
          level: this.comment.rootId === 0 ? 2 : 3,
          replyUserId: this.comment.userId,
          userId: this.currentUser.id
        }
      }).then(res => {
        if (res.code === '200') {
          this.$notify.success('回复成功');
          this.showReply = false;
          this.replyContent = '';
          this.$emit('refresh-comment');
        } else {
          this.$notify.error(res.msg || '回复失败');
        }
      }).finally(() => {
        // 补充 finally 确保加载状态重置（原代码遗漏，精简后保留核心优化）
        this.isSubmitting = false;
      });
    },
    // 子评论刷新：仅保留事件透传核心逻辑
    handleRefresh() {
      this.$emit('refresh-comment');
    }
  }
};
</script>

<style scoped>
/* 评论项：仅保留核心内边距 */
.comment-item {
  padding: 8px 0;
}

/* 评论头部：flex 布局核心样式 */
.comment-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 4px;
}

/* 头像：精简尺寸和边距，保留核心样式 */
.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
}

/* 用户内容区：占满剩余宽度 */
.user-content {
  flex: 1;
}

/* 用户名：精简字体和颜色，保留核心视觉 */
.username {
  font-size: 12px;
  font-weight: bold;
  color: #ff6781;
  margin-bottom: 5px;
}

/* 评论内容：精简字体和行高，保留核心展示 */
.comment-text {
  font-size: 12px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 4px;
  margin-left: 2px;
}

/* @回复标识：仅保留颜色 */
.reply-at {
  color: #ff6781;
  margin-right: 2px;
}

/* 时间和回复按钮：精简布局和字体 */
.time-reply {
  display: flex;
  align-items: center;
  font-size: 9px;
  color: #999;
  margin-left: 2px;
}

.time {
  margin-right: 8px;
}

/* 回复按钮：精简 hover 效果，保留核心交互 */
.reply-btn {
  color: #999;
  padding: 0;
  font-size: 12px;
  transition: color 0.2s;
}

.reply-btn:hover {
  color: #ff6781;
  background: transparent;
}

/* 回复输入框：精简边距和背景，保留核心样式 */
.reply-input {
  margin: 6px 0 6px 36px;
  padding: 6px;
  background: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
}

.reply-textarea {
  margin-bottom: 6px;
  resize: none;
  border-radius: 4px;
  border: 1px solid #ddd;
  font-size: 13px;
}

/* 回复按钮组：仅保留布局 */
.reply-btn-group {
  display: flex;
  justify-content: flex-end;
  gap: 6px;
}

/* 子评论：仅保留缩进核心样式 */
.children-comments {
  margin-top: 6px;
  padding-left: 36px;
}

.children-list {
  padding-top: 4px;
}
</style>
